<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>初始化配置</title>
    <link rel="stylesheet" type="text/css" href="components/milligram/dist/milligram.css">
  </head>
  <body>
      <script>
          const ipcRenderer = require('electron').ipcRenderer;
          const psychokinesis = require('psychokinesis');
          const uuid = require('uuid');
          const request = require('request');
          
          let waiting = false;
          
          function showErrorMsg(msg) {
              let prompt = document.getElementById("prompt");
              prompt.innerHTML = '<strong>' + msg + '</strong>';
              prompt.style.display = 'inline';
          }

          function changeLocalMode(localMode) {
              let selfField = document.getElementById("selfField");
              let entryField = document.getElementById("entryField");
              
              selfField.disabled = entryField.disabled = localMode;
          }
          
          function submitConfig() {
              if (waiting) {
                  showErrorMsg('请稍等...');
                  return false;
              }

              let localMode = document.getElementById("localModeField").checked;
              if (localMode === true) {
                  ipcRenderer.send('set-config', {domain: 'localhost'});
                  return;
              }
              
              let selfNode = document.getElementById("selfField").value;
              let entryNode = document.getElementById("entryField").value;
              
              let self = selfNode.split(':');
              let entry = entryNode.split(':');
              
              if (self.length === 1 && 
                  entry.length === 3 && 
                  /^(?!:\/\/)([a-zA-Z0-9]+\.)?[a-zA-Z0-9][a-zA-Z0-9-]+\.[a-zA-Z]{2,6}?$/i.test(self[0])
              ) {
                  let config = {
                      domain: self[0],
                      entryNode: {
                          host: entry[0],
                          dhtPort: entry[1],
                          proxyPort: entry[2]
                      }
                  };
                  
                  let psyc = psychokinesis.createServer(config, (req, resp) => {}); 
                  
                  waiting = true;
                  
                  psyc.on('ready', () => {
                      psyc.destroy();
                      ipcRenderer.send('set-config', config);
                      
                      waiting = false;
                  });
                  
                  psyc.on('error', (err) => {
                      psyc.destroy();
                      showErrorMsg('入口地址不可达！');
                      
                      waiting = false;
                  });
              } else {
                  showErrorMsg('域名或者入口地址格式不正确！');
              }
              
              return false;
          };
      </script>
      <form onsubmit="return submitConfig()">
          <fieldset>
              <label for="selfField">域名：</label>
              <input type="text" placeholder="mydomain.com" id="selfField">
              <label for="entryField">入口地址：</label>
              <input type="text" placeholder="entrynode.com:8181:18181" id="entryField">
              <div class="float-right">
                  <input type="checkbox" id="localModeField" onchange="changeLocalMode(this.checked)">
                  <label class="label-inline" for="localModeField">开启本地模式</label>
              </div>
              <div>
                  <span id="prompt" style="display: none; color: red"></span>
              </div>
              <input class="button-primary" type="submit" value="确定">
          </fieldset>
      </form>
      <script>
          document.getElementById("selfField").value = uuid.v4() + '.psy';
          
          request('https://coding.net/u/covertness/p/nodelist/git/raw/master/nodes.txt', function (error, response, body) {
              if (!error && response.statusCode == 200) {
                  let nodeList = new Buffer(body, 'base64').toString('ascii');
                  let nodes = JSON.parse(nodeList);
                  
                  if (nodes.length > 0) {
                      let randNode = nodes[Math.floor(Math.random() * nodes.length)];
                      document.getElementById("entryField").value = randNode.host + ':' + randNode.dhtPort + ':' + randNode.proxyPort;
                  }
                }
          });
      </script>
  </body>
</html>